#!/bin/bash
#2020年7月22日20:59:23
#auto config tomcat web
#by author www.jfedu.net
########################
TOMCAT_DOMAINS="$*"
TOMCAT_VER="8.0.50"
JAVA_VER="1.8.0_131"
JAVA_DIR="/usr/java"
TOMCAT_DIR="/usr/local"
JAVA_SOFT="jdk${JAVA_VER}.tar.gz"
TOMCAT_SOFT="apache-tomcat-${TOMCAT_VER}.tar.gz"

if [ $# -eq 0 ];then
	echo -e "\033[32m---------------\033[0m"
	echo -e "\033[32mUsage:{/bin/sh $0 v1.jf.com|v2.jf.com v3.jf.com|help}\033[0m"
	exit 1
fi

grep -ai "^export" /etc/profile|grep -ai "JAVA_HOME" >/dev/null
if [ $? -ne 0 ];then
	#Install JAVA JDK
	ls -l $JAVA_SOFT 
	tar -xzvf $JAVA_SOFT
	mkdir -p $JAVA_DIR/
	\mv jdk$JAVA_VER $JAVA_DIR/
	ls -l $JAVA_DIR/jdk$JAVA_VER/
	$JAVA_DIR/jdk$JAVA_VER/bin/java -version
	cat>>/etc/profile<<-EOF
	export JAVA_HOME=$JAVA_DIR/jdk$JAVA_VER
	export CLASSPATH=\$CLASSPATH:\$JAVA_HOME/lib:\$JAVA_HOME/jre/lib
	EOF
	source /etc/profile
fi

MAX_PORT=$(for i in $(find /usr/local/ -name "server.xml");do grep -ai "port=" $i;done|awk -F"=" '{print $2}'|awk '{print $1}'|sed 's/\"//g'|sort -nr|head -1)
if [ -z $MAX_PORT ];then
	#Install Tomcat WEB
	ls -l $TOMCAT_SOFT
	tar -xzvf $TOMCAT_SOFT >/dev/null
	mkdir -p $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/
	\mv apache-tomcat-$TOMCAT_VER/* $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/ >/dev/null 2>&1
	$TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/bin/startup.sh
	ps -ef|grep "$TOMCAT_DOMAINS"
	sleep 5 
	netstat -tnlp|grep -aiwE "6001|7001|8001"
	setenforce 0
	systemctl stop firewalld.service
	service iptables stop
else
	for TOMCAT_DOMAINS in $TOMCAT_DOMAINS
	do
		MAX_PORT=$(for i in $(find /usr/local/ -name "server.xml");do grep -ai "port=" $i;done|awk -F"=" '{print $2}'|awk '{print $1}'|sed 's/\"//g'|sort -nr|head -1)
		#Install Tomcat WEB
		PORT1=$(expr $MAX_PORT - 2000 + 1)	
		PORT2=$(expr $MAX_PORT - 1000 + 1)	
		PORT3=$(expr $MAX_PORT + 1)	
		ls -l $TOMCAT_SOFT
		tar -xzvf $TOMCAT_SOFT >/dev/null
		mkdir -p $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/
		\mv apache-tomcat-$TOMCAT_VER/* $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/ >/dev/null 2>&1
		sed -i "s/6001/$PORT1/g" $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/conf/server.xml
		sed -i "s/7001/$PORT2/g" $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/conf/server.xml
		sed -i "s/8001/$PORT3/g" $TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/conf/server.xml
		$TOMCAT_DIR/tomcat_$TOMCAT_DOMAINS/bin/startup.sh
		ps -ef|grep "$TOMCAT_DOMAINS"
		sleep 5
		netstat -tnlp|grep -aiwE "$PORT1|$PORT2|$PORT3"
		setenforce 0
		systemctl stop firewalld.service
		service iptables stop
	done
fi
